package dtls;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;

import org.eclipse.californium.elements.RawData;
import org.eclipse.californium.elements.RawDataChannel;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;

public class DtlsClient {

	public static void main(String[] args) throws Exception {
		
		InputStream in = DtlsServer.class.getResourceAsStream(DtlsServer.KEY_STORE_LOCATION);
		KeyStore keyStore = KeyStore.getInstance("jks");
		keyStore.load(in, DtlsServer.KEY_STORE_PASSWORD.toCharArray());
		in.close();
		
		KeyStore trustStore = KeyStore.getInstance("jks");
		in = DtlsServer.class.getResourceAsStream(DtlsServer.TRUST_STORE_LOCATION);
		trustStore.load(in, DtlsServer.TRUST_STORE_PASSWORD.toCharArray());
		in.close();
		
		Certificate[] cert = new Certificate[1];
		cert[0] = trustStore.getCertificate("root");
		
		DtlsConnectorConfig.Builder builder = 
				new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
		builder.setIdentity((PrivateKey)keyStore.getKey("client", DtlsServer.KEY_STORE_PASSWORD.toCharArray()), 
				keyStore.getCertificateChain("client"), true);
		builder.setTrustStore(cert);
		final DTLSConnector connector = new DTLSConnector(builder.build());
		connector.setRawDataReceiver(new RawDataChannel() {
			
			@Override
			public void receiveData(RawData raw) {
				System.out.println("client receive data:" + new String(raw.getBytes()));
				connector.destroy();
			}
		});
		connector.start();
		connector.send(new RawData("client data".getBytes(), 
				new InetSocketAddress("localhost", DtlsServer.DEFAULT_PORT)));
	}
}
